package com.ts.auth;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ts.common.security.dto.UserLoginDto;
import org.junit.jupiter.api.Test;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTDemo {

    Algorithm sign = Algorithm.HMAC256("Java2207-ts-pom");

    @Test
    public void creatToken() {
        // 1.认证成功准备用户的信息
        UserLoginDto userLoginDto = new UserLoginDto();
        userLoginDto.setUserId(001);
        Date createTime = new Date();
        userLoginDto.setCreateTime(createTime);
        Long l = createTime.getTime() + 1000 * 60 * 30L;
        userLoginDto.setExpireTime(new Date(l));

        // 2.使用JWT生成一个Token(在这个token中要把用户的信息揉入进去)
        JWTCreator.Builder builder = JWT.create(); // 创建一个JWT的Builder对象

        Map<String, Object> header = new HashMap<>();
        header.put("h1", "v1");
        header.put("h2", "v2");
        builder.withHeader(header); // 给JWT的头部设置数据【头部】

        // 给JWT的载荷(这个部门主要保存用户的数据)部门设置数据【载荷】
        builder.withClaim("name", "admin");
        builder.withClaim("age", 30);
        builder.withClaim("falg", true);
        builder.withClaim("sal", 300.1);
        builder.withClaim("user", JSON.toJSONString(userLoginDto));

//        builder.withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 20)); // 设置过期时间

        // 设置签名【签名】生成和校验的时候都是通过签名
        String token = builder.sign(sign);
        System.out.println(token);
    }

    @Test
    public void chekcToken() {

        String token = "eyJoMSI6InYxIiwiaDIiOiJ2MiIsInR5cCI6IkpXVCIsImFsZyI6IkhTMjU2In0.eyJuYW1lIjoiYWRtaW4iLCJmYWxnIjp0cnVlLCJleHAiOjE2Nzc0ODA0NTYsInVzZXIiOiJ7XCJjcmVhdGVUaW1lXCI6MTY3NzQ4MDQzNjMwNSxcImV4cGlyZVRpbWVcIjoxNjc3NDgyMjM2MzA1LFwidXNlcklkXCI6MX0iLCJhZ2UiOjMwLCJzYWwiOjMwMC4xfQ.igz429XqrTRmm7NyGPiliXxncKvwcEpk_068X6GZrQQ";

        // 认证token的合法性，如果认证失败该方法就会抛出认证异常
        DecodedJWT verify = JWT.require(Algorithm.HMAC256("Java2207-ts-pom")).build().verify(token);
        System.out.println(verify);

        String name = verify.getClaim("name").asString();
        int age = verify.getClaim("age").asInt();
        boolean flag = verify.getClaim("falg").asBoolean();
        double sal = verify.getClaim("sal").asDouble();
        String user = verify.getClaim("user").asString();
        System.out.println("name:" + name);
        System.out.println("age:" + age);
        System.out.println("flag:" + flag);
        System.out.println("sal:" + sal);
        System.out.println("user:" + user);

        String v1 = verify.getHeaderClaim("h1").asString();
        System.out.println("v1:" + v1);

    }
}
